package cn.kow.kmall.security;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.core.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-30 17:56
 * @Modified By:
 */
@Slf4j
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error("登录失败，" + e.getMessage(), e);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonUtils.toJson(KmallResult.build(KmallResultEnum.UNAUTHORIZED)));
    }
}
